<?php


namespace app\service\snowflake\server;



use app\service\snowflake\IdWorker;

class RedisCountServer implements CountServerInterFace
{
    private $redis = null;

    /**
     * RedisCountService constructor.
     * @param $config
     * @throws \Exception
     */
    public function __construct($config)
    {
        $this->redis = new \Redis();
        if (!isset($config['host']) || !isset($config['port'])) {
            throw new \Exception('invalid redis config');
        }
        $this->redis->connect($config['host'], $config['port']);
        if (isset($config['dbIndex'])) {
            $this->redis->select($config['dbIndex']);
        }
        if (isset($config['auth'])) {
            $this->redis->auth($config['auth']);
        }
        return $this;
    }

    /**
     * Notes:getSequenceId
     * @author  zhangrongwang
     * @date 2018-12-26 10:42:20
     * @param $key
     * @return int $sequenceId
     */
    public function getSequenceId($key)
    {
        $sequenceId = $this->redis->incr($key) - 1;
        $this->redis->expire($key, 5);
        return $sequenceId;
    }
}

############# 使用方法 #######################

//生成id
$IdWorker = IdWorker::getIns();
$id = $IdWorker->id();
//反向解析id
$idInfo = $IdWorker->parse($id);
//分布式，设置机器id
$dataCenterId = 2;
$machineId = 5;
$IdWorker = IdWorker::getIns($dataCenterId,$machineId);
$id = $IdWorker->id();
//redis配置
$resdisConfig = ['host'=>'redis host','port'=>'redis port','dbIndex'=>'redis dbIndex','auth'=>'redis auth'];
$IdWorker = IdWorker::getIns()->setRedisConutServer($resdisConfig);
$id = $IdWorker->id();


